//
//  KATGifImage.m
//  KATFramework
//
//  Created by Kantice on 16/7/25.
//  Copyright © 2016年 KatApp. All rights reserved.
//

#import "KATGifImage.h"

@implementation KATGifImage


#pragma -mark 类方法

//通过文件路径获取实例
+ (instancetype)imageWithFile:(NSString *)file
{
    return [self imageWithFile:file andSize:CGSizeZero];
}


//获取实例
+ (instancetype)imageWithFile:(NSString *)file andSize:(CGSize)size
{
    KATGifImage *gif=[[[self alloc] init] autorelease];
        
    gif.animationTimingMode=kCAMediaTimingFunctionLinear;
    gif.bounds=CGRectMake(0, 0, 0, 0);
    gif.contentMode=UIViewContentModeScaleAspectFit;
    gif.bounds=CGRectMake(0, 0, size.width, size.height);
    
    //获取图片资源
    CGImageSourceRef src=CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:file], NULL);
    
    gif.frameCount=CGImageSourceGetCount(src);
    gif.frames=[KATArray arrayWithCapacity:(int)gif.frameCount];
    gif.gifDuration=0.0;
    
    NSMutableArray *values=[NSMutableArray arrayWithCapacity:(NSUInteger)gif.frameCount];//动画值数组
    NSMutableArray *times=[NSMutableArray arrayWithCapacity:(NSUInteger)gif.frameCount];//动画时间数组
    NSMutableArray *delays=[NSMutableArray arrayWithCapacity:(NSUInteger)gif.frameCount];//每帧延迟时间
    
    float repeat=-1;//重复次数
    
    //遍历
    for(unsigned long long i=0;i<gif.frameCount;i++)
    {
        //获取每帧
        CGImageRef frame=CGImageSourceCreateImageAtIndex(src, (size_t)i, NULL);
        UIImage *img=[UIImage imageWithCGImage:frame];
        
        [values addObject:img];
        [gif.frames put:img];
        
        if(i==0)//首帧作为静态图片
        {
            gif.layer.contents=(__bridge id)frame;
        }
        
        CGImageRelease(frame);
        
        //获取每帧信息
        NSDictionary *dict=(__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(src, (size_t)i, NULL);
//        NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
        
        //获取尺寸
        if(gif.bounds.size.width<=0 || gif.bounds.size.height<=0)
        {
            gif.bounds=CGRectMake(0, 0, [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue]/[KATAppUtil screenScale], [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue]/[KATAppUtil screenScale]);
        }
        
        //获取每帧时长
        NSDictionary *gifDict=[dict valueForKey:(NSString *)kCGImagePropertyGIFDictionary];
        [delays addObject:[gifDict valueForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime]];
        
        //总时长
        gif.gifDuration=gif.gifDuration+[[gifDict valueForKey:(NSString*)kCGImagePropertyGIFUnclampedDelayTime] floatValue];
        
        //重复次数
        if(i==0)
        {
            if([gifDict valueForKey:(NSString *)kCGImagePropertyGIFLoopCount])
            {
                repeat=[[gifDict valueForKey:(NSString *)kCGImagePropertyGIFLoopCount] floatValue];
            }
        }
        
        [dict release];
    }
    
    CFRelease(src);
    
    //计算动画时长
    float time=0;
    
    for(int i=0;i<delays.count;i++)
    {
        float t=[[delays objectAtIndex:i] floatValue];
        time+=t;
        
        [times addObject:@(time/gif.gifDuration)];
    }
    
    //生成动画
    gif.gifAnimation=[gif animationWithMode:SPRITE_MODE_CONTENTS keyValues:values keyTimes:times duration:gif.gifDuration repeat:repeat autoreverses:NO delay:0];
    
    return gif;
}


#pragma -mark 对象方法

//播放
- (void)play
{
    if(_gifAnimation)
    {
        [self startAnimation:_gifAnimation andDelay:0];
    }
}


//显示某一帧
- (void)displayWithFrame:(int)frame
{
    [self clearAnimations];
    
    if(frame>=0 && frame<_frames.length)
    {
        self.layer.contents=(__bridge id)((UIImage *)[_frames get:frame]).CGImage;
    }
}


//释放内存
- (void)dealloc
{
    [_frames release];
    [_gifAnimation release];
    
    [super dealloc];
}

@end
